package com.njust.diary.dao;
import com.njust.diary.po.User;
import com.njust.diary.util.DBUtil;
import com.njust.diary.vo.Result;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class UserDao {

    public User queryUserByName(String userName){

        String sql="select * from tb_user where uname =?";
        List<Object> params =new ArrayList<>();
        params.add(userName);
        User user= (User) BaseDao.queryRow(sql,params,User.class);


        return  user;
    }


public User queryUser(String userName){
    User user=null;
    Connection connection =null;
    PreparedStatement preparedStatement =null;
    ResultSet resultSet = null;
    try{
connection=DBUtil.getConnection();
String sql="select * from tb_user where uname =?";//获取sql对象
preparedStatement =connection.prepareStatement(sql);
preparedStatement.setString(1,userName);//设置参数
resultSet =preparedStatement.executeQuery();//返回结果
if (resultSet.next()){
    user = new User();
    user.setUserId(resultSet.getInt("userId"));
    user.setUname(userName);
    user.setUpwd(resultSet.getString("upwd"));
    user.setHead(resultSet.getString("head"));
    user.setNick(resultSet.getString("nick"));
    user.setMotto(resultSet.getString("motto"));

}


    }catch(Exception e){
        e.printStackTrace();
    }finally {
        DBUtil.close(resultSet,preparedStatement,connection);
    }



return user;
}


    public User queryUserByNickAndUserId(String nick, Integer userId) {
        String sql="select * from tb_user where nick = ? and UserId != ?";
        List<Object> params =new ArrayList<>();
        params.add(nick);
        params.add(userId);
        User user =(User) BaseDao.queryRow(sql,params,User.class);
        return user;


    }

    public int updateUser(User user) {
        String sql ="update tb_user set nick = ?, motto = ?, head = ? where userId = ?";
        List<Object> params=new ArrayList<>();
        params.add(user.getNick());
        params.add(user.getMotto());
        params.add(user.getHead());
        params.add(user.getUserId());
        int row =BaseDao.executeUpdate(sql,params);
        return row;



    }


    public int insertUser(User user){
        String sql = "INSERT INTO tb_user (uname, upwd, nick, head, motto) VALUES (?, ?, ?, ?, ?);";
        List<Object> params=new ArrayList<>();
        params.add(user.getUname());
        params.add(user.getUpwd());
        params.add(user.getNick());
        params.add(user.getHead());
        params.add(user.getMotto());
        int row =BaseDao.executeUpdate(sql,params);
        return row;
    }

    public User queryUserByUname(String uname){
        String sql="select * from tb_user where uname = ?";
        List<Object>params=new ArrayList<>();
        params.add(uname);
        User user=(User)BaseDao.queryRow(sql,params,User.class);
        return user;
    }
}
